package com.qgs.secsgem.mq.controller;

import com.qgs.secsgem.common.utils.R;
import com.qgs.secsgem.mq.Constant.SecsGemTimeout;
import com.qgs.secsgem.mq.entity.CallbackMessageEntity;
import com.qgs.secsgem.mq.entity.MQMessage;
import com.qgs.secsgem.mq.producer.component.RabbitSender;
import com.qgs.secsgem.mq.secsgem.AsyncFuture;
import com.qgs.secsgem.mq.secsgem.SendedList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 蔡翔
 * @Date: 2019/10/12 15:15
 * @Version 1.0
 */
@RestController
@RequestMapping("/mq")
public class MQController {
    private static final Logger logger = LoggerFactory.getLogger(MQController.class);

    @Autowired
    RabbitSender rabbitSender;

    @PostMapping("/eapResponse")
    /**
     *  desc : 回复EAP的request 的回调接口（向rabbitmq中发送消息（direct模式））
     *  MES => DC(数据采集中间件) => MQ => EAP
     */
    public R eapResponse(@RequestBody CallbackMessageEntity callbackMessageEntity){
        try {
            logger.info("MES => EAP (EAP_Response), 状态：DC已收到 ,内容："+ callbackMessageEntity.toString());
            //properties 这里的参数是写在MQ消息 header里面的，如果EAP端 需要某些参数 可以写在这里，eap去取更方便一些
            Map<String,Object> properties = new HashMap<>();
            properties.put("equipmentName","PID001");
            properties.put("transitionId", callbackMessageEntity.getMqMessage().getHeader().getTransactionId());
            rabbitSender.reply(callbackMessageEntity.getMqMessage(),properties, callbackMessageEntity.getExchangeName(), callbackMessageEntity.getRoutingKey());
            logger.info("MES => EAP (EAP_Response) , 状态：DC已发送给MQ , 内容："+ callbackMessageEntity.toString());
            return R.ok("回复成功");
        }catch (Exception e){
            logger.error("MES => EAP (EAP_Response) , 状态：DC处理异常 , 内容："+ callbackMessageEntity.toString());
            return R.error().put("result",e.getMessage());
        }
    }

    //need
    @PostMapping("/mesRequest")
    /**
     *  desc : MES给EAP发送远程指令（MES_Request）（向rabbitmq中发送消息（direct模式））
     *  MES => DC(数据采集中间件) => MQ => EAP
     *  return :返回 的就是这个指令的回复指令
     *      1 = 成功
     *      其他 = 异常
     */
    public R mesRequest(@RequestBody CallbackMessageEntity callbackMessageEntity){
        try {
            String transitionId = callbackMessageEntity.getMqMessage().getHeader().getTransactionId();
            MQMessage mqMessage = callbackMessageEntity.getMqMessage();
            String exchangeName =  callbackMessageEntity.getExchangeName();
            String routingKey =  callbackMessageEntity.getRoutingKey();

            logger.info("MES => EAP (MES_Request), 状态：DC已收到 , 内容："+ callbackMessageEntity.toString());
            rabbitSender.sendDirect(mqMessage,exchangeName,routingKey);
            logger.info("MES => EAP (MES_Request) , 状态：DC已发送给MQ , 内容："+ callbackMessageEntity.toString());

            AsyncFuture<MQMessage> add = SendedList.add(transitionId,mqMessage);
            MQMessage mqMessageResponse = add.get(SecsGemTimeout.T3_TIMEOUT);
            return R.ok().put("responseMessage",mqMessageResponse);
        }catch (Exception e){
            logger.error("MES => EAP (MES_Request) , 状态：DC处理异常 , 内容："+ callbackMessageEntity.toString());
            return R.error(2,e.getMessage());
        }
    }

    @PostMapping("/mesRequestNoW")
    /**
     *  desc : MES给EAP发送远程指令（MES_Request）（向rabbitmq中发送消息（direct模式））
     *  MES => DC(数据采集中间件) => MQ => EAP
     *  return :返回 的就是这个指令的回复指令
     *      1 = 成功
     *      其他 = 异常
     */
    public R mesRequestNoW(@RequestBody CallbackMessageEntity callbackMessageEntity){
        try {
            String transitionId = callbackMessageEntity.getMqMessage().getHeader().getTransactionId();
            MQMessage mqMessage = callbackMessageEntity.getMqMessage();
            String exchangeName =  callbackMessageEntity.getExchangeName();
            String routingKey =  callbackMessageEntity.getRoutingKey();

            logger.info("MES => EAP (MES_Request), 状态：DC已收到 , 内容："+ callbackMessageEntity.toString());
            rabbitSender.sendDirect(mqMessage,exchangeName,routingKey);
            logger.info("MES => EAP (MES_Request) , 状态：DC已发送给MQ , 内容："+ callbackMessageEntity.toString());

            return R.ok();
        }catch (Exception e){
            logger.error("MES => EAP (MES_Request) , 状态：DC处理异常 , 内容："+ callbackMessageEntity.toString());
            return R.error(2,e.getMessage());
        }
    }
}
